/**
 * 
 */
package org.o14x.alpha.ui.views.foldertree;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.o14x.alpha.ui.controller.UIController;
import org.o14x.alpha.ui.coolbar.AddressBarContributionItem;
import org.o14x.alpha.ui.views.folder.FolderView;

/**
 * SelectionListener for the folder tree.
 * 
 * @author Olivier DANGREAUX
 */
public class FolderTreeSelectionListener implements ISelectionListener, ISelectionChangedListener {
	/**
	 * log.
	 */
	private Log log = LogFactory.getLog(FolderTreeSelectionListener.class);
	
	/**
	 * UIController;
	 */
	private UIController uiController;

	/**
	 * Creates a new instance of FolderTreeSelectionListener.
	 *
	 * @param uiController the UIController.
	 */
	public FolderTreeSelectionListener(UIController uiController) {
		this.uiController = uiController;
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		if (part instanceof FolderTreeView) {
			File selectedFolder = (File) ((TreeSelection) selection).getFirstElement();
			changeSelectedFolder(selectedFolder);
		}
	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		File selectedFolder = (File) ((TreeSelection) event.getSelection()).getFirstElement();
		changeSelectedFolder(selectedFolder);
	}

	/**
	 * Changes the current folder according to the folder selected in the folder tree.
	 * 
	 * @param selectedFolder The selected folder in the folder tree;
	 */
	private void changeSelectedFolder(File selectedFolder) {
		if (selectedFolder != null) {
			uiController.getDomain().getCurrentExplorerTab().navigate(selectedFolder);

			FolderView currentFolderView = uiController.getDomain().getCurrentExplorerTab().getFolderView();
			if (currentFolderView != null) {
				currentFolderView.update();
			}

			AddressBarContributionItem addressBarContributionItem = uiController.getUi().getAddressBarContributionItem();
			if (addressBarContributionItem != null) {
				addressBarContributionItem.update();
			}
		}
	}

	/**
	 * Returns the value of uiController.
	 *
	 * @return The value of uiController.
	 */
	public UIController getUiController() {
		return uiController;
	}

	/**
	 * Sets the value of uiController.
	 *
	 * @param uiController The value of uiController to set.
	 */
	public void setUiController(UIController uiController) {
		this.uiController = uiController;
	}
}
